package com.hunk.core.auth.service.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hunk.core.auth.entity.User;
import com.hunk.core.auth.repository.UserRepository;
import com.hunk.core.auth.repository.UserSpecifications;
import com.hunk.core.auth.service.UserService;
import com.hunk.core.web.model.JpaOmGridPage.JpaPageRequest;
import com.hunk.core.web.model.JpaOmGridPage.JpaPageResponse;
import com.hunk.utils.exception.CustomizeException;

/**
 * Description :<br>
 * 
 * @author HunkDeng
 * @since 2013-4-30
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
    private UserRepository userRepository;//注入UserRepository

    @Override
    @Transactional
    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    @Transactional(readOnly=true)
    public User findById(String id) {
        return userRepository.findOne(id);
    }

    @Override
    @Transactional
    public void deleteById(String id) {
        userRepository.delete(id);
    }
    
    @Override
    @Transactional
    public void delete(User user) throws NotFoundException {
    	if (userRepository.findOne(user.getId()) == null) {
    		logger.warn("No Role found with id : {" + user.getId() + "}");
    		throw new NotFoundException("No Role found with id : {" + user.getId() + "}");
    	}
    	userRepository.delete(user);
    }

	@Override
	@Transactional(readOnly=true)
	public User checkUser(User user) throws CustomizeException {
		User _user = userRepository.findByUsername(user.getUsername());
		if (_user == null) 
			throw new CustomizeException("User Not Exist!");
		if (!StringUtils.equals(_user.getPassword(), user.getPassword())) 
			throw new CustomizeException("Username or Password Error!"); 
		if (!_user.isEnabled())
			throw new CustomizeException("User has been disable");
		return _user;
	}

	@Override
	@Transactional(readOnly=true)
	public JpaPageResponse<User> findPageByParams(JpaPageRequest<User> pageRequest) {
		Specification<User> userSpec = 
				UserSpecifications.UserSpecQueryOne(pageRequest.getExtraData());
		return new JpaPageResponse<User>(
				userRepository.findAll(
						Specifications.where(userSpec),
						pageRequest.setSort(UserRepository.defaultSort).getPageRequest()
						)
				);
	}
}
